<template>
	<view>
		<view>
			<block v-for="(oneRoundLots, roundIdx) in seatLotteryRules" :key="roundIdx">
				<view class="popup_group">
					<view class="lay-c-c">
						<text class="title">第{{roundIdx+1}}场</text>
					</view>
					<view class="popup_group_item">
						<view v-if="roundIdx==0" style="width: 100%;">
							<view class="mg-b-md">所有运动员抽取：</view>
							<checkbox-group @change="lotItemNewPartitionChange($event, roundIdx, 0)">
								<block v-for="(parti, partiIdx) in oneRoundLots[0].new_partitions" :key="partiIdx">
									<label class="pd-l-lg">
										<checkbox :value="parti.partitionNum+''" :checked="parti.checked==1" />{{parti.partitionNum}} 区
									</label>
								</block>
							</checkbox-group>
							<view class="lay-sa-c-c mg-t-xxl">
								<!-- 暂时不做重置功能
								<button class="mini-btn bk-orange" type="warn" size="mini" @click="resetRoundLottery(roundIdx)" style="margin-left: 40rpx;">重置</button>
								-->
								<!-- 暂时不用，由系统自动开启
								<button class="mini-btn bk-green" type="warn" size="mini" @click="openRoundLottery(roundIdx)" style="margin-left: 40rpx;">{{rounds[roundIdx].drawLotsStatus==0?"开启摇号":"关闭摇号"}}</button>
								-->
							</view>
						</view>
						<view v-else style="width: 100%;">
							<block v-for="(lotItem, lotItemIdx) in oneRoundLots" :key="lotItemIdx">
								<view class="lay-sb-c-c" style="padding-bottom: 8rpx; border-bottom: solid 1px lightgray;">
									<view>摇号项{{lotItemIdx+1}} </view>
									<button v-if="lotItemIdx>0" class="mini-btn" type="warn" size="mini" @click="delLotItem(roundIdx, lotItemIdx)" style="margin-left: 40rpx;">删除</button>
								</view>
								<view class="pd-l-xl mg-b-xl">
									<view class="mg-v-md">分区运动员：</view>
									<checkbox-group @change="lotItemLastPartitionChange($event, roundIdx, lotItemIdx)">
										<block v-for="(parti, partiIdx) in lotItem.last_partitions" :key="partiIdx">
											<label class="pd-l-lg">
												<checkbox :value="parti.partitionNum+''" :checked="parti.checked==1" />{{parti.partitionNum}} 区
											</label>
										</block>
									</checkbox-group>
									<view class="mg-t-sm mg-b-md">抽取：</view>
									<checkbox-group @change="lotItemNewPartitionChange($event, roundIdx, lotItemIdx)">
										<block v-for="(parti, partiIdx) in lotItem.new_partitions" :key="partiIdx">
											<label class="pd-l-lg">
												<checkbox :value="parti.partitionNum+''" :checked="parti.checked==1" />{{parti.partitionNum}} 区
											</label>
										</block>
									</checkbox-group>
								</view>
								<view v-if="lotItemIdx==(oneRoundLots.length-1)" class="lay-c-c" style="margin-top: -10rpx;">
									<button class="mini-btn" type="warn" size="mini" @click="addLotItem(roundIdx)" style="margin-left: 40rpx;">添加摇号项</button>
								</view>
							</block>
							<view class="lay-sa-c-c mg-t-xxl">
								<!-- 暂时不做重置功能
								<button class="mini-btn bk-orange" type="warn" size="mini" @click="resetRoundLottery(roundIdx)" style="margin-left: 40rpx;">重置</button>
								-->
								<!-- 暂时不用，由系统自动开启
								<button class="mini-btn bk-green" type="warn" size="mini" @click="openRoundLottery(roundIdx)" style="margin-left: 40rpx;">{{rounds[roundIdx].drawLotsStatus==0?"开启摇号":"关闭摇号"}}</button>
								-->
							</view>
						</view>
					</view>
				</view>
			</block>
		</view>

		<view class="lay-c-c">
			<view class="btn radius2 bk-blue white" style="width: 50%;" @click="doSubmit">保存抽签规则</view>
		</view>
		
		<view class="mg-t-md pd-md">
			<view class="title">说明</view>
			<view>1. 第一场抽签前务必在报名名单中确认所有参赛选手已通过审核。</view>
			<view>2. 设置分区对调规则时务必保证起始分区选择了本场次所有需要使用的分区。</view>
			<view>3. 重置功能将清空本场所有选手已经抽取钓位，务必经现场讨论确认后再清空。</view>
		</view>

	</view>
</template>

<script>
const app = getApp();
import { navigateTo, serialize, setStorage, getStorage, removeStorage, Loading, hideLoading, Modal } from '../../libs/uniApi.js';

import store from '@/store';
import {genDefaultPartition, correctSeats, MyTip} from '../../components/ssty/common.js';

import {queryForEditRound, saveForEditRound, openRoundLottery, resetRoundLottery} from '@/api/fsh.js'

export default {
	data() {
		
		return {
			seatLotteryRules: [
				[{
					// last_partitions仅在第2场往后有效，表示上一场指定分区的人抽取new_partitions中分区
					last_partitions: [{partitionNum: 1, checked: 1}], 		
					new_partitions: [{partitionNum: 1, checked: 1}]
				}]
			],
			
			rounds: [{
				drawLotsStatus: 0, // 抽签状态: 0-抽签关闭 1-抽签开放
			}]
		};
	},
	onLoad(opt) {
		this.merId = opt.merId;
		this.product_id = opt.prodId;
		this.raceId = opt.raceId;
		
		this.seatLotteryRules = [];
		
		// 查询钓塘列表
		queryForEditRound(this.merId, this.raceId).then(res=>{
			this.rounds = res.entity.rounds;
			
			let rn = res.entity.race.round_number, pn = res.entity.race.partition_number;
			this.partitionNumber = pn;
			
			if(res.entity.race.seat_lottery_rules) {
				this.seatLotteryRules = JSON.parse(res.entity.race.seat_lottery_rules);
				
				if(this.seatLotteryRules.length != rn) {
					if(this.seatLotteryRules.length > rn) {
						this.seatLotteryRules.splice(rn, this.seatLotteryRules.length - rn);
					}
					else if(this.seatLotteryRules.length < rn) {
						while(this.seatLotteryRules.length < rn) {
							this.seatLotteryRules.push([this.genDefaultPartiLots()]);
						}
					}
				}
				
				this.seatLotteryRules.forEach(oneRoundLots=>{
					if(oneRoundLots.length != pn) {
						if(oneRoundLots.length > pn) {
							oneRoundLots.splice(pn, oneRoundLots.length - pn);
						}
						else if(oneRoundLots.length < pn) {
							while(oneRoundLots.length < pn) {
								oneRoundLots.push(this.genDefaultPartiLots());
							}
						}
					}
				})
			}
			else {
				if(!rn || !pn) {
					Modal('先配置场次', '', {showCancel: false})
					.then(() => {
						uni.navigateBack();
					})
					return;
				}

				for(let i = 0; i < rn; i++)
					this.seatLotteryRules.push([this.genDefaultPartiLots()]);
			}
			
			console.log("queryForEditRound ok", this.seatLotteryRules);
		}).catch(e=>{
			console.error(e);
			Modal('查询失败，请稍后重试', '', {showCancel: false})
			.then(() => {
				uni.navigateBack();
			})
		});
	},
	methods: {
		genDefaultPartiLots() {
			let partis = [];
			for(let i = 0; i < this.partitionNumber; i++)
				partis.push({partitionNum: (i+1), checked: 1});
				
			return {
				last_partitions: partis, 		
				new_partitions: partis
			};
		},
		
		delLotItem(roundIdx, lotItemIdx) {
			this.seatLotteryRules[roundIdx].splice(lotItemIdx, 1);
			console.log("delLotItem " + lotItemIdx + " from round " + roundIdx, this.seatLotteryRules);
			
			this.seatLotteryRules = JSON.parse(JSON.stringify(this.seatLotteryRules)); // 赋值让UI刷新
		},
		
		addLotItem(roundIdx) {
			this.seatLotteryRules[roundIdx].push(this.genDefaultPartiLots());
			console.log("addLotItem to round "+roundIdx, this.seatLotteryRules);
			
			this.seatLotteryRules = JSON.parse(JSON.stringify(this.seatLotteryRules)); // 赋值让UI刷新
		},
		
		lotItemLastPartitionChange(e, roundIdx, lotItemIdx) {
			// debugger
			//console.log("lotItemPartitionChange", JSON.stringify(e), roundIdx, lotItemIdx)
			//let ary = e.detail.value.map(a=>{partitionNum: parseInt(a), checked: 1})
			
			let parts = [];
			for(let i = 0; i < this.partitionNumber; i++) {
				let checked = undefined !== e.detail.value.find(a=>parseInt(a)==i+1)
				parts.push({partitionNum: i+1, checked: checked});
			}
			
			this.seatLotteryRules[roundIdx][lotItemIdx].last_partitions = parts;
		},
		
		lotItemNewPartitionChange(e, roundIdx, lotItemIdx) {
			// debugger
			// console.log("lotItemNewPartitionChange", JSON.stringify(e), roundIdx, lotItemIdx)
			
			let parts = [];
			for(let i = 0; i < this.partitionNumber; i++) {
				let checked = undefined !== e.detail.value.find(a=>parseInt(a)==i+1)
				parts.push({partitionNum: i+1, checked: checked});
			}
			
			this.seatLotteryRules[roundIdx][lotItemIdx].new_partitions = parts;
		},
		
		resetRoundLottery(roundIdx) {
			
		},
		
		openRoundLottery(roundIdx) {
			let onOff = this.rounds[roundIdx].drawLotsStatus == 0 ? 1 : 0;
			openRoundLottery(this.raceId, roundIdx+1, onOff).then(res=>{
				this.rounds[roundIdx].drawLotsStatus = onOff;
			}).catch(err=>{
				
			})
		},
		
		doSubmit() {
			let postData = {
				raceId: this.raceId,
				step: 3,
				seatLotteryRules: JSON.stringify(this.seatLotteryRules),
			};
			
			uni.showLoading({
				title: '保存中...'
			});
			
			saveForEditRound(this.raceId, postData)
			.then(res => {
				hideLoading()
				Modal('保存成功', '', {
					showCancel: false
				}).then(() => {
					uni.navigateBack();
				})
			})
			.catch(errMsg => {
				uni.hideLoading();
				console.log("race_manage_edit_draw_lots, saveForEditRound fail", errMsg);
				MyTip(errMsg.msg);
			});
		},
	}
};
</script>

<style lang="scss" scoped>

@import "@/leui.scss";

.popup_group {
	background: #fff;
	margin: 31rpx auto;
	width: 710rpx;
	font-size: 30rpx;
	border-radius: 10rpx;
	.popup_group_item {
		padding: 32rpx 30rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		.popup_group_item_value {
			display: flex;
			align-items: center;
			.popup_group_item_message {
				margin-right: 15rpx;
				color: #bbbbbb;
				max-width: 400rpx;
				&_value {
					color: #000;
				}
			}
			.iconfont {
				color: #bbbbbb;
			}
			input {
				text-align: right;
			}
		}
	}
	// > view:not(:last-child) {
	// 	border-bottom: 1px solid #eeeeee;
	// }
}

</style>
